import React from 'react';
import { getCurrentHeight } from 'Utils';
import { mapConfig } from 'Constants/config';
import { Icon } from 'antd-mobile';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import Api from 'Utils/api';
import dialog from 'Utils/dialog';
import './../ShiAnMap/index.scss';
import './index.scss';

class NavicationPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectDept: {},
      organise: [],
      currentLocation: {}
    };
    this.LoadMapDept = ::this.LoadMapDept;
    this.getCurrentInfo = ::this.getCurrentInfo;
  }

  componentDidMount() {
    this.initMap();
    this.initOrganise();
  }
  getCurrentInfo() {
    const self = this;
    this.location.getCurrentPosition((e) => {
      if (this.location.getStatus() === 0 || this.location.getStatus() === 1) {
        self.setState({
          currentLocation: {
            longitude: e.lnglat.lng,
            latitude: e.lnglat.lat
          }
        }, () => {
          self.currentLocationInfo();
        });
      }
    })
  }
  // 获取机构信息并根据sessionStorage中得信息获取当前选中得机构
  initOrganise() {
    const api = new Api({
      method: 'GET',
      path: '/depts/level',
      success: (res) => {
        const organiseId = parseInt(sessionStorage.getItem('organiseId'), 10);
        this.setState({
          organise: res,
          selectDept: organiseId ? res.filter(item => item.id === organiseId)[0] : {}
        }, () => {
          this.getCurrentInfo();
          this.LoadMapDept();
        });
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  currentLocationInfo() {
    const { selectDept, currentLocation } = this.state;
    const icon = new T.Icon({ iconUrl: 'images/icon_map.png', iconSize: new T.Point(20, 24), iconAnchor: new T.Point(10, 24) });
    // 向地图上添加当前位置自定义标注
    const marker = new T.Marker(
      new T.LngLat(currentLocation.longitude, currentLocation.latitude), { icon }
    );
    this.map.addOverLay(marker);
    // 改变地图中心
    if (!selectDept.longitude && !selectDept.latitude) {
      this.map.panTo(
        new T.LngLat(currentLocation.longitude, currentLocation.latitude), this.map.getZoom()
      );
    } else {
      this.map.panTo(new T.LngLat(selectDept.longitude, selectDept.latitude), this.map.getZoom());
      this.initSearchLine()
    }
  }
  // 绘制路线
  initSearchLine() {
    const { selectDept, currentLocation } = this.state;
    // 当两点在相同位置
    if (
      selectDept.longitude === currentLocation.longitude &&
      selectDept.latitude === currentLocation.latitude) {
      return;
    }
    const startLngLat = new T.LngLat(currentLocation.longitude, currentLocation.latitude);
    const endLngLat = new T.LngLat(selectDept.longitude, selectDept.latitude);
    this.drivingRoute.search(startLngLat, endLngLat);
  }
  searchResult(result) {
    const routes = result.getNumPlans();
    for (let i = 0; i < routes; i++) {
      // 获得单条方案结果对象
      const plan = result.getPlan(i);
      this.createRoute(plan.getPath());
    }
  }
  // 画track
  createRoute(lnglats) {
    this.Track = new T.CarTrack(this.map, {
      interval: 20,
      speed: 10,
      dynamicLine: true,
      Datas: lnglats,
      carstyle: { display: false, iconUrl: '', width: 0, height: 0 },
      polylinestyle: { color: '#1480FF', width: 5, opacity: 0.9 }
    });
  }
  LoadMapDept() {
    const { organise, selectDept } = this.state;
    const self = this;
    for (let i = 0, len = organise.length; i < len; i++) {
      const icon = new T.Icon({ iconUrl: organise[i].id === selectDept.id ? 'images/icon_organise_light.png' : 'images/icon_organise_normal.png', iconSize: new T.Point(24, 24), iconAnchor: new T.Point(12, 24) });
      // 向地图上添加自定义标注
      const markerBusi = new T.Marker(
        new T.LngLat(organise[i].longitude, organise[i].latitude), { icon }
        );
      self.map.addOverLay(markerBusi);
      markerBusi.addEventListener('click', () => {
        this.props.dispatch(routerActions.push(`/navigation/detail/${organise[i].id}`));
      })
    }
  }
  initMap() {
    // 经纬度地图显示；
    this.map = new T.Map('map');
    // 双击放大地图；
    this.map.enableDoubleClickZoom();
    // 地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    // 地图惯性拖拽；
    this.map.enableInertia();
    // 设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(mapConfig.longitude, mapConfig.latitude), 16);
    // 路线初始化
    const config = {
      policy: 0,
      onSearchComplete: this.searchResult.bind(this)
    };
    this.drivingRoute = new T.DrivingRoute(this.map, config);
    this.location = new T.Geolocation();
  }
  handleSearch() {
    this.props.dispatch(routerActions.push('/navigation/search'));
  }
  render() {
    const height = `${getCurrentHeight(0)}rem`;
    const { selectDept } = this.state;
    return (
      <div className="shian-map-page navigation-page">
        <div className="map" id="map" style={{ height }} />
        <div className="search-wrap" onClick={this.handleSearch.bind(this)}>
          <Icon type="search" />
          <div className="label">{selectDept.name ? <span className="organise-name">{selectDept.name}</span> : '请输入'}</div>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}
export default connect(mapStateToProps)(NavicationPage);
